<template>
  <div class="grid-carousel">
    <el-button class="nav-btn left" @click="prev" circle>
      <el-icon>
        <ArrowLeft />
      </el-icon>
    </el-button>
    <div class="grid-track">
      <div class="grid-row" v-for="row in rows" :key="row">
        <div class="grid-item" v-for="col in cols" :key="col">
          <img v-if="gridData[(page * rows * cols) + (row - 1) * cols + (col - 1)]"
            :src="gridData[(page * rows * cols) + (row - 1) * cols + (col - 1)].img"
            :alt="gridData[(page * rows * cols) + (row - 1) * cols + (col - 1)].title || ''" />
        </div>
      </div>
    </div>
    <el-button class="nav-btn right" @click="next" circle>
      <el-icon>
        <ArrowRight />
      </el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const props = defineProps({
  items: { type: Array, required: true },
  rows: { type: Number, default: 2 },
  cols: { type: Number, default: 3 },
})

const page = ref(0)
const totalPage = computed(() =>
  Math.ceil(props.items.length / (props.rows * props.cols))
)
const gridData = computed(() => props.items)

const prev = () => {
  page.value = (page.value - 1 + totalPage.value) % totalPage.value
}
const next = () => {
  page.value = (page.value + 1) % totalPage.value
}
</script>

<style lang="scss" scoped>
.grid-carousel {
  position: relative;
  width: 600px;
  margin: 0 auto;

  .grid-track {
    width: 100%;
    background: #fff;
    border-radius: 18px;
    box-shadow: 0 4px 24px #e0e7ff;
    padding: 18px;

    .grid-row {
      display: flex;
      gap: 18px;
      margin-bottom: 18px;

      &:last-child {
        margin-bottom: 0;
      }

      .grid-item {
        flex: 1;
        height: 120px;
        border-radius: 12px;
        overflow: hidden;
        background: #f3f4f6;
        display: flex;
        align-items: center;
        justify-content: center;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 12px;
        }
      }
    }
  }

  .nav-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 10;

    &.left {
      left: -48px;
    }

    &.right {
      right: -48px;
    }
  }
}
</style>